package net.hzlj.platform.enterprise.socket.mina;

import net.hzlj.platform.enterprise.BootApp;
import net.hzlj.platform.enterprise.common.Constant;

import android.content.Intent;
import android.util.Log;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * @Description:
 * @Author: Jason Zhang
 * @Date: 2016/12/5 0005
 */

public class MinaClientHandler extends IoHandlerAdapter {

    public static final String TAG = MinaClientHandler.class.getSimpleName();


    public MinaClientHandler(){
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        super.exceptionCaught(session, cause);
        Log.i(TAG,"exceptionCaught id:" + session.getId() + ",cause message:" + cause.getMessage());
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        super.messageReceived(session, message);
        Log.i(TAG,"messageReceived id:" + session.getId() + ",message:" + message.toString());
        Intent intent = new Intent(Constant.Intent.ACTION_SOCKET_MESSAGE_RECEIVED);
        intent.putExtra("message",message.toString());
        BootApp.getAppContext().sendBroadcast(intent);
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
//        session.close(true);//加上这句话实现短连接的效果，向客户端成功发送数据后断开连接
        Log.i(TAG,"messageSent id:" + session.getId() + ",message:" + message.toString());
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
        Log.i(TAG,"sessionCreated id:" + session.getId());
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status)
            throws Exception {
        super.sessionIdle(session, status);
        Log.i(TAG,"sessionIdle id:" + session.getId() + ",status:" + status.toString());
    }
    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
        //客户端上线
        Log.i(TAG,"sessionOpened id:" + session.getId());
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
        //客户端下线
        Log.i(TAG,"sessionClosed id:" + session.getId());
    }
}
